package transform;

import beans.SenSorReading;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class KeyByAndRollAggregation {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //从文件中读取数据
        DataStreamSource<String> inputStream = env.readTextFile("src/main/resources/sensor.txt");

        //转换成自定义的类型
//        SingleOutputStreamOperator<SenSorReading> dataStream = inputStream.map(new MapFunction<String, SenSorReading>() {
//            @Override
//            public SenSorReading map(String s) throws Exception {
//                String[] fileds = s.split(",");
//                return new SenSorReading(fileds[0], new Long(fileds[1]), new Double(fileds[2]));
//            }
//        });
        SingleOutputStreamOperator<SenSorReading> dataStream = inputStream.map(line -> {
            String[] fields = line.split(",");
            return new SenSorReading(fields[0], new Long(fields[1]), new Double(fields[2]));
        });

        /**
         * key的两种实现方式
         * 第一种：如果数据类型是元组（Tuple）的话，直接使用所分区的位置即可
         * 第二种：字段名称，也就是自定义类的分区属性名
         */
        KeyedStream<SenSorReading, Tuple> keyByStream = dataStream.keyBy("id");
//        KeyedStream<SenSorReading, String> keyByStream02 = dataStream.keyBy(data -> data.getId());

        //滚动聚合
        /**
         * 什么是滚动聚合？
         * 就是不同的在更新，来一条数据就会更新一条数据
         */
        SingleOutputStreamOperator<SenSorReading> resultStream = keyByStream.max("temperature");
        /**
         * maxBy和max的区别？
         * max的是取最大值，但是朱慧注意所要取的那个元素，最后输出的结果是索取元素的最大值，但是其他元素不一定是和其匹配的
         * maxBy记录的是整条元素
         */
        SingleOutputStreamOperator<SenSorReading> maxByresultStream = keyByStream.maxBy("temperature");
        maxByresultStream.print("maxBy");
        resultStream.print("max");
        env.execute();
    }
}
